// 使用组合式API将页面滚动逻辑抽象为独立的API
import { onActivated, onDeactivated, onMounted, onUnmounted } from "vue";
// import { useThrottleFn } from "@vueuse/core";

export default (
  handler: () => void,
  when: "onMounted" | "onActivated" = "onMounted"
) => {
  // 确定需要执行代码的生命周期
  const [on, off] =
    when == "onMounted"
      ? [onMounted, onUnmounted]
      : [onActivated, onDeactivated];
  // 监听 window 滚动事件函数，使用节流函数提高效率
  const onScroll = () => {
    if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 1)
      handler();
  };
  on(() => {
    window.addEventListener("scroll", onScroll);
  });
  off(() => {
    window.removeEventListener("scroll", onScroll);
  });
};
